package com.frxuexi.myroom.view

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.Button
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil3.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.RoutePath
import com.frxuexi.lib_base.UiState
import com.frxuexi.lib_base.room.Leave
import com.frxuexi.myroom.intent.LeaveIntent
import com.frxuexi.myroom.viewmodel.LeaveViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

var modi = Modifier
    .fillMaxWidth()
    .background(Color.White, RoundedCornerShape(20.dp))
    .border(1.dp, Color.LightGray, RoundedCornerShape(20.dp))
    .padding(20.dp)
/**
 * 请假申请页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RoomLeavePage(navHostController: NavHostController, vm: LeaveViewModel = hiltViewModel()) {
    var uname by remember {
        mutableStateOf(MMKV.defaultMMKV().decodeString("name", "未登录").toString())
    }
    var role by remember {
        mutableStateOf(MMKV.defaultMMKV().decodeString("role","").toString())
    }
    var type by remember {
        mutableStateOf("事假")
    }
    val today = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
    var start by remember {
        mutableStateOf(today)
    }

    var end by remember {
        mutableStateOf(today)
    }
    var reason by remember {
        mutableStateOf("")
    }

    var isShow by remember {
        mutableStateOf(false)
    }
    val state = rememberDatePickerState()

    var isStart by remember {
        mutableStateOf(true)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        ToastUtils.showLong("申请成功")
                        navHostController.popBackStack()
                    }

                    else -> {}
                }

            }
        }
    })

    Column(modifier = Modifier.fillMaxSize()) {
        BaseTitle(title = "请假申请", navHostController = navHostController)
        Column(
            Modifier.padding(horizontal = 20.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            Row(modi) {
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=797474174,3214837072&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1732294800&t=f472f47d1015da000b2194ee3b7a3c4a",
                    contentDescription = "",
                    modifier = Modifier
                        .size(80.dp)
                        .clip(CircleShape),
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.width(10.dp))
                Column(Modifier.height(80.dp), verticalArrangement = Arrangement.SpaceAround) {
                    Text(text = uname)
                    Text(text = role)
                }
            }
            Row(
                horizontalArrangement = Arrangement.spacedBy(10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "请假类型:")
                RadioButton(selected = type == "事假", onClick = { type = "事假" })
                Text(text = "事假")
                RadioButton(selected = type == "病假", onClick = { type = "病假" })
                Text(text = "病假")
            }
            Row(
                horizontalArrangement = Arrangement.spacedBy(10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "开始时间:")
                OutlinedTextField(
                    value = start,
                    onValueChange = { start = it },
                    readOnly = true,
                    trailingIcon = {
                        Icon(
                            imageVector = Icons.Default.DateRange,
                            contentDescription = "",
                            Modifier.clickable {
                                isShow = true
                                isStart = true
                            })
                    })
            }
            Row(
                horizontalArrangement = Arrangement.spacedBy(10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "结束时间:")
                OutlinedTextField(
                    value = end,
                    onValueChange = { end = it },
                    readOnly = true,
                    trailingIcon = {
                        Icon(
                            imageVector = Icons.Default.DateRange,
                            contentDescription = "",
                            Modifier.clickable {
                                isShow = true
                                isStart = false
                            })
                    })
            }
            Row(
                horizontalArrangement = Arrangement.spacedBy(10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = "请假原因:")
                OutlinedTextField(value = reason, onValueChange = { reason = it }, label = {
                    Text(text = "请输入请假原因")
                })
            }
            Button(modifier = Modifier.fillMaxWidth(), onClick = {
                if (!reason.isNullOrEmpty()) {
                    val uid = MMKV.defaultMMKV().decodeLong("uid", -1)
                    val role = MMKV.defaultMMKV().decodeString("role", "").toString()
                    val time =
                        SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                    val leave = Leave(
                        uid = uid,
                        uname = uname,
                        role = role,
                        type = type,
                        startTime = start,
                        endTime = end,
                        reason = reason,
                        createTime = time,
                        status = "未审核"
                    )
                    vm.sendIntent(
                        LeaveIntent.addLeave(leave)
                    )
                } else {
                    ToastUtils.showLong("原因不能为空")
                }
            }) {
                Text(text = "提交")
            }
        }

    }
    if (isShow) {
        DatePickerDialog(onDismissRequest = { isShow = false }, confirmButton = {
            Text(text = "确认", Modifier.clickable {
                val time = SimpleDateFormat("yyyy-MM-dd").format(state.selectedDateMillis)
                if (isStart)
                    start ="$time 09:00:00"
                else
                    end = "$time 18:00:00"
                isShow = false
            })
        }) {
            DatePicker(state = state)
        }
    }
}

/*
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DateChoice(isShow: Boolean,closeClick:()->Unit,date:(String)->Unit){
    val state = rememberDatePickerState()


}*/
